<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'rd:rd32:rdrecord32:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdrecords32List>
        <BasicTable @register="registerRdrecords32Table" @row-click="handleRdrecords32RowClick">
          <template #summary>
            <Table.Summary fixed>
              <Table.Summary.Row>
                <Table.Summary.Cell :index="0" :col-span="1" :style="{ textAlign: 'center', fontWeight: 'bold'}"
                  >合计</Table.Summary.Cell
                >
                <Table.Summary.Cell :index="2" :col-span="13"></Table.Summary.Cell>
                <Table.Summary.Cell :index="1" :style="{ textAlign: 'right', fontWeight: 'bold' }">
                  {{ totalIqty.sumFqty }}</Table.Summary.Cell
                >
                <Table.Summary.Cell :index="1" :col-span="6"></Table.Summary.Cell>
                <Table.Summary.Cell :index="1" :style="{ textAlign: 'right', fontWeight: 'bold' }">
                  {{ totalIqty.sumCkQty }}</Table.Summary.Cell
                >
                <Table.Summary.Cell :index="1" :style="{ textAlign: 'right', fontWeight: 'bold' }">
                  {{ totalIqty.sumPickQty }}</Table.Summary.Cell>
              </Table.Summary.Row>
            </Table.Summary>
          </template>

        </BasicTable>
        <!-- <a-button class="mt-2" @click="handleRdrecords32Add" v-auth="'rd:rd32:rdrecord32:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsRdRd32Rdrecord32Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Rdrecord32, rdrecord32Save, rdrecord32Form } from '/@/api/wms/rd/rd32/rdrecord32';
  import { companyTreeData } from '/@/api/sys/company';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { Table } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('rd.rd32.rdrecord32');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Rdrecord32>({} as Rdrecord32);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增出库任务单') : t('查看出库任务单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('公司名称'),
      field: 'companyCode',
      fieldLabel: 'companyName',
      component: 'TreeSelect',
      componentProps: {
        api: companyTreeData,
        allowClear: true,
      },
      dynamicDisabled: true,
    },
    {
      label: t('发货单号'),
      field: 'fbillno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('发货日期'),
      field: 'fdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('发运方式'),
      field: 'fyfs',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('购货单位内码'),
      field: 'fsupplyid',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
      dynamicDisabled: true,
    },
    {
      label: t('购货单位编码'),
      field: 'fsupplierno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      ifShow: false,
    },
    {
      label: t('购货单位名称'),
      field: 'fsuppliername',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    {
      label: t('客户联系人'),
      field: 'fcontacts',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('客户电话'),
      field: 'fphone',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('到站'),
      field: 'fdz',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    {
      label: t('省份'),
      field: 'fprovince',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('城市'),
      field: 'fcity',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    {
      label: t('是否打印'),
      field: 'fifprinteger',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no_chinese',
      },
      dynamicDisabled: true,
    },
    {
      label: t('紧急程度'),
      field: 'furgentlevel',
      component: 'Select',
      componentProps: {
        dictType: 'wms_jj_level',
      },
      dynamicDisabled: true,
    },
    {
      label: t('部门'),
      field: 'fdepartment',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('业务员'),
      field: 'femp',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('主管'),
      field: 'fempz',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('制单'),
      field: 'fbiller',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('是否打包'),
      field: 'fifpack',
      component: 'Select',
      componentProps: {
        dictType: 'sys_yes_no_chinese',
      },
      dynamicDisabled: true,
    },
    {
      label: t('公司编码'),
      field: 'companyCode',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      show: false,
    },
    {
      label: t('备注'),
      field: 'fexplanation',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
        rows: 2,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('出库明细'),
      field: 'rdrecords32List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdrecords32List',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 6, md: 24 },
  });

  const [registerRdrecords32Table, rdrecords32Table] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'i-ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleRdrecords32Delete.bind(this, record),
    //       },
    //       auth: 'rd:rd32:rdrecord32:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
    showIndexColumn: false,
  });

  async function setRdrecords32TableData(_res: Recordable) {
    rdrecords32Table.setColumns([
      {
        title: t('发货单行号'),
        dataIndex: 'fentryid',
        width: 100,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('订单号'),
        dataIndex: 'forderno',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('订单行号'),
        dataIndex: 'forderentryid',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        fixed: 'left',
      },
      {
        title: t('订单主表ID'),
        dataIndex: 'forderid',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('打包单位'),
        dataIndex: 'fcustomerdb',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('收货单位'),
        dataIndex: 'fcustomersh',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('收货联系人'),
        dataIndex: 'fperson',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('电话'),
        dataIndex: 'fphone',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: false,
      },
      {
        title: t('手机'),
        dataIndex: 'fmobilephone',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('收货地址'),
        dataIndex: 'faddress',
        width: 300,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('物料内码'),
        dataIndex: 'fitemid',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('物料代码'),
        dataIndex: 'fitemno',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('物料名称'),
        dataIndex: 'fitemname',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('辅助属性类别'),
        dataIndex: 'f109',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('数量'),
        dataIndex: 'fqty',
        width: 80,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 26,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('累计出库数'),
        dataIndex: 'sumCkQty',
        width: 130,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 26,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('累计拣货数'),
        dataIndex: 'sumPickQty',
        width: 130,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 26,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('行备注'),
        dataIndex: 'fremarks',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('仓库ID'),
        dataIndex: 'fstockid',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('仓库名称'),
        // dataIndex: 'fstockno',
        dataIndex: 'fstockname',
        // dataLabel: 'fstockname',
        width: 130,
        align: 'left',
        // editRow: false,
        // editComponent: 'TreeSelect',
        // editComponentProps: ({ record }) => {
        //   return {
        //     api: basWarehouseTreeData,
        //     canSelectParent: false,
        //     showSearch: false,
        //     allowClear: true,
        //     onChange: (value, label) => {
        //       rdrecords32Table.updateTableDataRecord(record.id, {
        //         ...record,
        //         fstockno: value,
        //         fstockname: label,
        //       });
        //     },
        //   };
        // },
        // editRule: false,
      },
      {
        title: t('仓库编码'),
        dataIndex: 'fstockno',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('品质'),
        dataIndex: 'fpz',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('要求到货日期'),
        dataIndex: 'freturndate',
        width: 120,
        align: 'center',
        editRow: false,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
      {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
    ]);
    rdrecords32Table.setTableData(record.value.rdrecords32List || []);
  }

  function handleRdrecords32RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRdrecords32Add() {
    rdrecords32Table.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: false,
    });
  }

  function handleRdrecords32Delete(record: Recordable) {
    rdrecords32Table.deleteTableDataRecord(record);
  }

  async function getRdrecords32List() {
    let rdrecords32ListValid = true;
    let rdrecords32List: Recordable[] = [];
    for (const record of rdrecords32Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rdrecords32ListValid = false;
      }
      rdrecords32List.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rdrecords32Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rdrecords32List.push({
        ...record,
        status: '1',
      });
    }
    if (!rdrecords32ListValid) {
      throw { errorFields: [{ name: ['rdrecords32List'] }] };
    }
    return rdrecords32List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rdrecord32Form(data);
    record.value = (res.rdrecord32 || {}) as Rdrecord32;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRdrecords32TableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.rdrecords32List = await getRdrecords32List();
      // console.log('submit', params, data, record);
      const res = await rdrecord32Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  const totalIqty = computed(() => {
    // 计算总报工数
    const tableData = rdrecords32Table.getDataSource();
    // const tableData = getDataSource.value;
    let sumFqty = tableData.reduce((total, item) => total + (item.fqty || 0), 0);
    let sumCkQty = tableData.reduce((total, item) => total + (item.sumCkQty || 0), 0);
    let sumPickQty = tableData.reduce((total, item) => total + (item.sumPickQty || 0), 0);
    return {
      sumFqty: sumFqty,
      sumCkQty: sumCkQty,
      sumPickQty: sumPickQty,
    };
  });
</script>
